package com.cqeec.bootdemo.filter;

import com.alibaba.fastjson.JSON;

import com.cqeec.bootdemo.common.BaseContext;
import com.cqeec.bootdemo.common.R;
import com.cqeec.bootdemo.entity.Employee;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("客户端ip:{}", request.getRemoteAddr());
        // 获取当前用户的访问的资源路径
        String requestURI = request.getRequestURI();  // /employee/page
        // 定义不需要进行登陆校验的资源
        String[] urls = new String[]{
                "/user/sendMsg",
                "/user/login",
                "/common/**",
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };
        // 判断当前访问的资源路径是否需要进行校验
        boolean flag = check(urls, requestURI);
        log.info("访问资源路径为：{},是否需要校验：{}", requestURI, flag);
        if (flag) {
            // 不需要校验，直接放行
            filterChain.doFilter(request, response);
            return;
        }
        // 获取名为Agent的请求头的值
        String agent = request.getHeader("Agent");
        // 判断请求是后台管理系统发出的还是移动端发出的
        if ("backend".equals(agent)) {
            // 需要进行登陆验证，判断session中是否存在用户信息
            if (request.getSession().getAttribute("employee") != null) {
                // 已经登陆
                //存用户的id到当前线程的ThreadLocal中
                Employee emp = (Employee) request.getSession().getAttribute("employee");
                BaseContext.setCurrentId(emp.getId());
                filterChain.doFilter(request, response);
                return;
            }
        } else if ("front".equals(agent)) {
            //4-2、判断登录状态，如果已登录，则直接放行
            if (request.getSession().getAttribute("user") != null) {
                Long userId = (Long) request.getSession().getAttribute("user");
                BaseContext.setCurrentId(userId);
                filterChain.doFilter(request, response);
                return;
            }
        }

        // 尚未登陆，跳转到登陆页面  NOTLOGIN与request.js response 对应
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径检查
     *
     * @param urls       所有的不需要进行登陆校验的资源路径表达式
     * @param requestURI 真实访问的资源路径
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return match; // true
            }
        }
        return false;
    }
}
